﻿using System;
using System.Data;
using System.Web.UI;
using System.Xml;
using System.Xml.Xsl;
using BLL;
using ET;
using Ext.Net;
using HTML;
using Roles;

namespace ERP.Modules
{
    public partial class Proposed : UserControl
    {
        #region[Define]

        private static bool _flag;
        //Nếu biến _flag = true thì xử lý hàm thêm vào bảng tạm đơn mua hàng,_flag = false thì thêm trực tiếp vào bảng đơn mua hàng

        private readonly Proposed_BLL clsProposed = new Proposed_BLL();
        private readonly Proposed_Detail_BLL clsProposedDetail = new Proposed_Detail_BLL();
        private DataTable dtGetMaterialOrderBuyCode;
        private DataTable dtGetOrderBuyCode;

        private DataTable dtGetProposed;
        private DataTable dtMaterial;
        private DataTable dtProposedTemp;
        private DataTable dtProposedTempEdit;

        #endregion

        #region[Controller]
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!X.IsAjaxRequest)
            {
                CheckPermisstion();
                GetDataProposed();
                GetDataOrderBuyCode();
                GetDataProposedTemp();
                btnEditMain.Disable(true);
                btnDel.Disable(true);
                btnExport.Disable(true);
                btnProposedReview.Disable(true);
            }
        }
        //-------Store-Datasource-----------------
        protected void StoreProposed_RefreshData(object sender, StoreReadDataEventArgs e)
        {
            txtSearchProposed.Text = string.Empty;
            SelectBoxReview.Text = string.Empty;
            txtDateBeginFillter.Text = string.Empty;
            txtDateEndFillter.Text = string.Empty;
            GetDataProposed();
        }
        protected void StoreProposed_Submit(object sender, StoreSubmitDataEventArgs e)
        {
            string format = FormatTypeProposed.Value.ToString();
            XmlNode xml = e.Xml;
            Response.Clear();

            switch (format)
            {
                case "xml":
                    string strXml = xml.OuterXml;
                    Response.AddHeader("Content-Disposition", "attachment; filename=submittedData.xml");
                    Response.AddHeader("Content-Length", strXml.Length.ToString());
                    Response.ContentType = "application/xml";
                    Response.Write(strXml);
                    break;

                case "xls":
                    Response.ContentType = "application/vnd.ms-excel";
                    Response.AddHeader("Content-Disposition", "attachment; filename=submittedData.xls");
                    var xtExcel = new XslCompiledTransform();
                    xtExcel.Load(Server.MapPath("Excel.xsl"));
                    xtExcel.Transform(xml, null, Response.OutputStream);

                    break;

                case "csv":
                    Response.ContentType = "application/octet-stream";
                    Response.AddHeader("Content-Disposition", "attachment; filename=submittedData.csv");
                    var xtCsv = new XslCompiledTransform();
                    xtCsv.Load(Server.MapPath("Csv.xsl"));
                    xtCsv.Transform(xml, null, Response.OutputStream);

                    break;
            }
            Response.End();
        }
        protected void StoreProposedTemp_RefreshData(object sender, StoreReadDataEventArgs e)
        {
            GetDataProposedTemp();
        }
        protected void StoreMaterialOrderBuyCode_RefreshData(object sender, StoreReadDataEventArgs e)
        {
            try
            {
                GetDataMaterialOrderBuyCode(int.Parse(SelectBoxOrderCode.SelectedItem.Value));
            }
            catch
            {
                clsFormat.Alert_ERROR("Lỗi", "Có lỗi xảy ra trong quá trình tải lại");
            }
        }
        protected void StoreOrderProposedReview_RefreshData(object sender, StoreReadDataEventArgs e)
        {
            try
            {
                GetDataProposedTempReview(int.Parse(HDProposed_OrderIdBuyOrderEdit.Text));
            }
            catch
            {
                clsFormat.Alert_ERROR("Lỗi", "Có lỗi xảy ra trong quá trình làm tươi !");
            }
        }
        //----------------------------------------
        protected void StoreOrderBuyProposedEdit_RefreshData(object sender, StoreReadDataEventArgs e)
        {
            try
            {
                GetDataProposedTempGridEdit(int.Parse(HD_OrderIdBuyOrderEdit.Text));
            }
            catch
            {
                clsFormat.Alert_ERROR("Lỗi", "Có lỗi xảy ra trong quá trình làm tươi vật tư !");
            }
        }
        //-------Tool-Bar-Main--------------------
        protected void MnOrderBuyWithOrder_Click(object sender, DirectEventArgs e)
        {
            Proposed_Detail_BLL.DeleteProposedTemp(int.Parse(Session["Users_Id"].ToString()));
            GetDataProposedTemp();
            GetDataOrderBuyCode();
            ClearText();
            WindowsProposedOrderBuyWithOrder.Show();
            _flag = true;
        }
        protected void MnOrderBuy_Click(object sender, DirectEventArgs e)
        {
        }
        protected void btnEdit_Click(object sender, DirectEventArgs e)
        {
        }
        protected void btnDel_Click(object sender, DirectEventArgs e)
        {
            var sm = grProposed.GetSelectionModel() as CheckboxSelectionModel;
            foreach (SelectedRow row in sm.SelectedRows)
            {
                var dtOrderDetailCheckStatus = new DataTable();
                dtOrderDetailCheckStatus = clsProposed.GetDataProposedGridEdit(int.Parse(row.RecordID));
                if (dtOrderDetailCheckStatus != null && dtOrderDetailCheckStatus.Rows.Count > 0)
                {
                    try
                    {
                        if (dtOrderDetailCheckStatus.Rows[0]["IsActive_B"].ToString() == "True")
                        {
                            clsFormat.Alert_ERROR("Thông Báo",
                                "Phiếu đề nghị đã được xét duyệt.Bạn không thể xoá phiếu đề nghị này này !");
                        }
                        else
                        {
                            Proposed_BLL.DeleteProposed(int.Parse(row.RecordID));
                            clsFormat.Alert_INFO("Thông Báo", "Xoá phiếu đề nghị nhập kho thành công !");
                        }
                    }
                    catch (Exception ex)
                    {
                        clsFormat.Alert_ERROR("Thông Báo", "Có lỗi xảy ra trong quá trình xoá mẫu tin !" + "<br/>" + ex);
                    }
                }
            }
            GetDataProposed();
        }
        protected void btnProposedReview_Click(object sender, DirectEventArgs e)
        {
            var sm = grProposed.GetSelectionModel() as CheckboxSelectionModel;
            foreach (SelectedRow row in sm.SelectedRows)
            {
                GetDataProposedTempReview(int.Parse(row.RecordID));
                GetDataProposedSumReview(int.Parse(row.RecordID));
                WindowProposedOrderReview.Show();
                sm.UpdateSelection();
            }
        }
        protected void btnFillter_Click(object sender, DirectEventArgs e)
        {
            GetDataProposedFillterDate();
        }
        protected void SelectBoxReview_Change(object sender, DirectEventArgs e)
        {
            GetDataProposed();
        }
        //--Tool-Bar-Window-Order-With-Order------
        protected void btnProposedSaveOrderBuyOrder_Click(object sender, DirectEventArgs e)
        {
            if (txtCustomerAliasOrderBuyOrderProposed.Text == string.Empty)
            {
                clsFormat.Alert_WARNING("Thông Báo", "Vui lòng điền vào mã nhà cung cấp !");
            }
            if (txtCustomerNameOrderBuyOrderProposed.Text == string.Empty)
            {
                clsFormat.Alert_WARNING("Thông Báo", "Vui lòng điền vào tên nhà cung cấp !");
            }
            if (txtChungTuOrderBuyOrderProposed.Text == string.Empty)
            {
                clsFormat.Alert_WARNING("Thông Báo", "Vui lòng chọn chứng từ mua hàng !");
            }
            if (txtCustomerAliasOrderBuyOrderProposed.Text != string.Empty
                && txtCustomerNameOrderBuyOrderProposed.Text != string.Empty
                && txtChungTuOrderBuyOrderProposed.Text != string.Empty)
            {
                InsertProposed();
            }
        }
        protected void btnProposedReloadOrderBuyOrder_Click(object sender, DirectEventArgs e)
        {
            GetDataProposedTemp();
        }
        protected void btnChooseOrderBuyCode_Click(object sender, DirectEventArgs e)
        {
            SelectBoxOrderCode.Clear();
            grMaterialWithOrder.GetStore().RemoveAll();
            GetDataOrderBuyCode();
            WindowMaterialWithOrder.Show();
            _flag = true;
        }
        protected void btnProposedExitToolOrderBuyOrder_Click(object sender, DirectEventArgs e)
        {
            Proposed_Detail_BLL.DeleteProposedTemp(int.Parse(Session["Users_Id"].ToString()));
            GetDataProposedTemp();
            WindowsProposedOrderBuyWithOrder.Close();
        }
        //--Tool-Bar-Window-Order-With-Order-Edit--
        protected void btnProposedSaveOrderBuyWithOrderEdit_Click(object sender, DirectEventArgs e)
        {
            UpdateProposed();
        }
        protected void btnProposedReloadOrderBuyWithOrderEdit_Click(object sender, DirectEventArgs e)
        {
            try
            {
                GetDataProposedTempGridEdit(int.Parse(HD_OrderIdBuyOrderEdit.Text));
            }
            catch
            {
                clsFormat.Alert_ERROR("Lỗi", "Có lỗi xảy ra trong quá trình làm tươi vật tư !");
            }
        }
        protected void btnChooseOrderBuyCodeEdit_Click(object sender, DirectEventArgs e)
        {
            if (HdReviewIsActiveEdit.Text == "True")
            {
                clsFormat.Alert_ERROR("Thông Báo",
                    "Phiếu đề nghị đã được xét duyệt.<br/>" + "Bạn không thể thay đổi phiếu đề nghị này !");
            }
            else
            {
                SelectBoxOrderCode.Clear();
                grMaterialWithOrder.GetStore().RemoveAll();
                GetDataOrderBuyCode();
                WindowMaterialWithOrder.Show();
                _flag = false;
            }
        }
        protected void btnProposedExitOrderBuyWithOrderEdit_Click(object sender, DirectEventArgs e)
        {
            WindownProposedOrderBuyWithOrderEdit.Close();
        }
        //--Tool-Bar-Window-Order-With-Order-Review-
        protected void btnProposedReviewWindow_Click(object sender, DirectEventArgs e)
        {
            ReviewProposed();
        }
        protected void btnProposedUnReviewWindow_Click(object sender, DirectEventArgs e)
        {
            UnReviewProposed();
        }
        protected void btnProposedReLoadReviewOrder_Click(object sender, DirectEventArgs e)
        {
            try
            {
                GetDataProposedTempReview(int.Parse(HDProposed_OrderIdBuyOrderEdit.Text));
            }
            catch
            {
                clsFormat.Alert_ERROR("Lỗi", "Có lỗi xảy ra trong quá trình làm tươi !");
            }
        }
        protected void btnProposedExitReviewOrder_Click(object sender, DirectEventArgs e)
        {
            WindowProposedOrderReview.Close();
        }
        //-----Tool-Bar-Update-Quality------------
        protected void btnProposedUpdateQuality_Click(object sender, DirectEventArgs e)
        {
            if (_flag)
            {
                UpdateQualityTemp();
            }
            else
            {
                UpdateQualityTempEdit();
            }
        }
        protected void btnProposedCancelOrder_Click(object sender, DirectEventArgs e)
        {
            WindowProposedUpdateQualityProposedMaterial.Close();
        }
        //----------Row-Command-----------------------
        protected void CellProposedUpdateQualityMaterial_Click(object sender, DirectEventArgs e)
        {
            var sm = grProposedTemp.GetSelectionModel() as CellSelectionModel;
            string ID = sm.SelectedCell.RecordID;
            GetDataProposedTempEditQuality(int.Parse(ID));
            sm.Clear();
            sm.UpdateSelection();
            WindowProposedUpdateQualityProposedMaterial.Show();
        }
        //-----------Edit-----------------------------
        protected void CellProposedUpdateQualityMaterialOrderBuyEdit_Click(object sender, DirectEventArgs e)
        {
            if (HdReviewIsActiveEdit.Text == "True")
            {
                clsFormat.Alert_ERROR("Thông Báo",
                    "Phiếu đề nghị đã được xét duyệt.<br/>" + "Bạn không thể thay đổi phiếu đề nghị này !");
            }
            else
            {
                var sm = grProposedTempOrderBuyWithOrderBuyEdit.GetSelectionModel() as CellSelectionModel;
                string ID = sm.SelectedCell.RecordID;
                GetDataProposedTempEditQuality(int.Parse(ID));
                sm.Clear();
                sm.UpdateSelection();
                WindowProposedUpdateQualityProposedMaterial.Show();
                _flag = false;
            }
        }
        protected void btnSelectMaterial_Click(object sender, DirectEventArgs e)
        {
            if (_flag)
            {
                #region[Insert-Material-Temp]

                var sm = grMaterialWithOrder.GetSelectionModel() as CheckboxSelectionModel;
                foreach (SelectedRow row in sm.SelectedRows)
                {
                    if (CheckInsertMaterial(int.Parse(row.RecordID)))
                    {
                        clsFormat.Alert_WARNING("Thông Báo",
                            "Vật tư này đã tồn tại.Vui lòng cập nhật số lượng và đơn giá !");
                    }
                    else
                    {
                        dtMaterial =
                            clsProposed.GetMaterialOrderBuyCode(int.Parse(SelectBoxOrderCode.SelectedItem.Value));
                        if (dtMaterial != null && dtMaterial.Rows.Count > 0)
                        {
                            var obj = new Proposed_Detail_Temp_ET();
                            obj.Order_Buy_Detail_Id = int.Parse(row.RecordID);
                            obj.Users_Id = int.Parse(Session["Users_Id"].ToString());
                            Proposed_Detail_BLL.InsertProposedDetailMaterialTemp(obj);
                            clsFormat.Alert_INFO("Thông Báo", "Thêm mới vật tư thành công !");
                            GetDataInfoCustomer(int.Parse(SelectBoxOrderCode.SelectedItem.Value));
                        }
                    }
                }
                GetDataProposedTemp();
                WindowMaterialWithOrder.Close();
                #endregion
            }
            else
            {
                #region[Insert-Material-Temp]

                var sm = grMaterialWithOrder.GetSelectionModel() as CheckboxSelectionModel;
                foreach (SelectedRow row in sm.SelectedRows)
                {
                    if (CheckInsertMaterialEdit(int.Parse(row.RecordID)))
                    {
                        clsFormat.Alert_WARNING("Thông Báo",
                            "Vật tư này đã tồn tại.Vui lòng cập nhật số lượng và đơn giá !");
                    }
                    else
                    {
                        dtMaterial =
                            clsProposed.GetMaterialOrderBuyCode(int.Parse(SelectBoxOrderCode.SelectedItem.Value));
                        if (dtMaterial != null && dtMaterial.Rows.Count > 0)
                        {
                            var obj = new Proposed_Detail_Temp_ET();
                            obj.Order_Buy_Detail_Id = int.Parse(row.RecordID);
                            obj.Users_Id = int.Parse(Session["Users_Id"].ToString());
                            obj.Proposed_ID = int.Parse(HD_OrderIdBuyOrderEdit.Text);
                            Proposed_Detail_BLL.InsertProposedDetailMaterialTempEdit(obj);
                            clsFormat.Alert_INFO("Thông Báo", "Thêm mới vật tư thành công !");
                        }
                    }
                }
                GetDataProposedTempGridEdit(int.Parse(HD_OrderIdBuyOrderEdit.Text));
                WindowMaterialWithOrder.Close();
                #endregion
            }
        }
        //--------Double-Click--------------------
        protected void DbClick_db(object sender, DirectEventArgs e)
        {
            if (CheckPermisstionDobclick())
            {
                HTML.clsFormat.Alert_ERROR("Thông Báo", "Bạn không được cấp quyền để sửa đổi !");
            }
            else
            {
                int Proposed_ID = int.Parse(e.ExtraParams["Proposed_ID"]);
                GetDataProposedTempGridEdit(Proposed_ID);
                WindownProposedOrderBuyWithOrderEdit.Show();
                txtChungTuNhapOrderBuyWithOrderEdit.ReadOnly = true;
                GetDataProposedSumEdit(Proposed_ID);
                _flag = false;
            }
        }
        //----------Select-Box----------------
        protected void SelectIndex_Change(object sender, DirectEventArgs e)
        {
            GetDataMaterialOrderBuyCode(int.Parse(SelectBoxOrderCode.SelectedItem.Value));
        }
        //----------Select-Box-Refresh--------
        protected void Refresh_Click(object sender, DirectEventArgs e)
        {
            SelectBoxOrderCode.Clear();
            grMaterialWithOrder.GetStore().RemoveAll();
            GetDataOrderBuyCode();
        }
        #endregion

        #region[Method]
        protected void GetDataProposed()
        {
            if (String.IsNullOrEmpty(SelectBoxReview.Text))
            {
                dtGetProposed = clsProposed.GetDataProposed(string.Empty);
                if (dtGetProposed != null && dtGetProposed.Rows.Count > 0)
                {
                    StoreProposed.DataSource = dtGetProposed;
                    StoreProposed.DataBind();
                }
                else
                {
                    grProposed.GetStore().RemoveAll();
                }
            }
            else
            {
                dtGetProposed = clsProposed.GetDataProposedFillterActive(int.Parse(SelectBoxReview.SelectedItem.Value));
                if (dtGetProposed != null && dtGetProposed.Rows.Count > 0)
                {
                    StoreProposed.DataSource = dtGetProposed;
                    StoreProposed.DataBind();
                }
                else
                {
                    grProposed.GetStore().RemoveAll();
                }
            }
        }
        private void GetDataProposedFillterDate()
        {
            if (String.IsNullOrEmpty(txtDateBeginFillter.Text) && String.IsNullOrEmpty(txtDateEndFillter.Text))
            {
                dtGetProposed = clsProposed.GetDataProposed(string.Empty);
                if (dtGetProposed != null && dtGetProposed.Rows.Count > 0)
                {
                    StoreProposed.DataSource = dtGetProposed;
                    StoreProposed.DataBind();
                }
                else
                {
                    grProposed.GetStore().RemoveAll();
                }
            }
            else
            {
                dtGetProposed = clsProposed.GetDataProposedFillterDate(txtDateBeginFillter.Text, txtDateEndFillter.Text);
                if (dtGetProposed != null && dtGetProposed.Rows.Count > 0)
                {
                    StoreProposed.DataSource = dtGetProposed;
                    StoreProposed.DataBind();
                }
                else
                {
                    grProposed.GetStore().RemoveAll();
                }
            }
        }
        protected void GetDataOrderBuyCode()
        {
            dtGetOrderBuyCode = clsProposed.GetOrderBuyCode();
            if (dtGetOrderBuyCode != null && dtGetOrderBuyCode.Rows.Count > 0)
            {
                StoreOrderCodeSelectBox.DataSource = dtGetOrderBuyCode;
                StoreOrderCodeSelectBox.DataBind();
            }
            else
            {
                SelectBoxOrderCode.GetStore().RemoveAll();
            }
        }
        protected void GetDataMaterialOrderBuyCode(int id)
        {
            dtGetMaterialOrderBuyCode = clsProposed.GetMaterialOrderBuyCode(id);
            if (dtGetMaterialOrderBuyCode != null && dtGetMaterialOrderBuyCode.Rows.Count > 0)
            {
                StoreMaterialOrderBuyCode.DataSource = dtGetMaterialOrderBuyCode;
                StoreMaterialOrderBuyCode.DataBind();
            }
            else
            {
                grMaterialWithOrder.GetStore().RemoveAll();
            }
        }
        protected void GetDataInfoCustomer(int id)
        {
            var dtGetDataInfoCustomer = new DataTable();
            dtGetDataInfoCustomer = clsProposed.GetMaterialOrderBuyCode(id);
            if (dtGetDataInfoCustomer != null && dtGetDataInfoCustomer.Rows.Count > 0)
            {
                txt_OrderBuyOrderBuyOrderProposed.Text = dtGetDataInfoCustomer.Rows[0]["Order_Buy_Id"].ToString();
                txtOrder_Buy_Detail_Id.Text = dtGetDataInfoCustomer.Rows[0]["Order_Buy_Detail_Id"].ToString();
                txtOrderBuyCode.Text = dtGetDataInfoCustomer.Rows[0]["Order_Buy_Code"].ToString();
                txtIDKhachHangOrderBuyOrderProposed.Text = dtGetDataInfoCustomer.Rows[0]["Customer_ID"].ToString();
                txtCustomerAliasOrderBuyOrderProposed.Text = dtGetDataInfoCustomer.Rows[0]["Customer_Alias"].ToString();
                txtCustomerNameOrderBuyOrderProposed.Text = dtGetDataInfoCustomer.Rows[0]["Customer_Name"].ToString();
                txtAddressOrderBuyOrderProposed.Text = dtGetDataInfoCustomer.Rows[0]["Customer_Address"].ToString();
            }
        }
        protected void GetDataProposedTemp()
        {
            if (Session["Users_Id"].ToString() != string.Empty)
            {
                dtProposedTemp = clsProposedDetail.GetDataProposedTemp(int.Parse(Session["Users_Id"].ToString()));
                if (dtProposedTemp != null && dtProposedTemp.Rows.Count > 0)
                {
                    StoreProposedTemp.DataSource = dtProposedTemp;
                    StoreProposedTemp.DataBind();
                }
                else
                {
                    grProposedTemp.GetStore().RemoveAll();
                }
            }
        }
        protected void GetDataProposedTempEditQuality(int id)
        {
            dtProposedTempEdit = clsProposedDetail.GetDataProposedTempEditQuality(id);
            if (dtProposedTempEdit != null && dtProposedTempEdit.Rows.Count > 0)
            {
                hdOrder_Buy_Detail_Id.Text = dtProposedTempEdit.Rows[0]["Order_Buy_Detail_Id"].ToString();
                hdIdOrderTemp.Text = dtProposedTempEdit.Rows[0]["Proposed_Detail_ID"].ToString();
                hdChietKhau.Text = dtProposedTempEdit.Rows[0]["Order_Detail_CK_Percent"].ToString();
                hdVAT.Text = dtProposedTempEdit.Rows[0]["Order_Detail_VAT_Percent"].ToString();
                hdPrice.Text = dtProposedTempEdit.Rows[0]["Order_Detail_Price"].ToString();
                hdMaterial.Text = dtProposedTempEdit.Rows[0]["MaterialsId"].ToString();
                hdQualityRemain.Text = dtProposedTempEdit.Rows[0]["Order_Detail_Quality_Remain"].ToString();
                hdNameMaterial.Text = dtProposedTempEdit.Rows[0]["Materials_Name"].ToString();
                txtSoLuong.Text = dtProposedTempEdit.Rows[0]["Proposed_Quality"].ToString();
                hdOrderQuanlity.Text = dtProposedTempEdit.Rows[0]["Order_Detail_Quality"].ToString();
            }
        }
        protected void GetDataProposedTempGridEdit(int id)
        {
            var dtGetDataProposedTempGridEdit = new DataTable();
            dtGetDataProposedTempGridEdit = clsProposed.GetDataProposedGridEdit(id);
            if (dtGetDataProposedTempGridEdit != null && dtGetDataProposedTempGridEdit.Rows.Count > 0)
            {
                StoreOrderBuyProposedEdit.DataSource = dtGetDataProposedTempGridEdit;
                StoreOrderBuyProposedEdit.DataBind();

                HD_OrderIdBuyOrderEdit.Text = dtGetDataProposedTempGridEdit.Rows[0]["Proposed_ID"].ToString();
                txtTaxCodeOrderBuyWithOrderEdit.Text =
                    dtGetDataProposedTempGridEdit.Rows[0]["Order_Buy_Code"].ToString();
                hdId_CustomerOrderBuyWithOrderEdit.Text =
                    dtGetDataProposedTempGridEdit.Rows[0]["Customer_ID"].ToString();
                txtAlias_OrderBuyWithOrderEdit.Text = dtGetDataProposedTempGridEdit.Rows[0]["Customer_Alias"].ToString();
                txtName_OrderBuyWithOrderEdit.Text = dtGetDataProposedTempGridEdit.Rows[0]["Customer_Name"].ToString();
                txtAddress_OrderBuyWithOrderEdit.Text =
                    dtGetDataProposedTempGridEdit.Rows[0]["Customer_Address"].ToString();
                txtChungTuNhapOrderBuyWithOrderEdit.Text =
                    dtGetDataProposedTempGridEdit.Rows[0]["Proposed_TaxCode"].ToString();
                txtNgayDatHang_OrderBuyWithOrderEdit.Text =
                    dtGetDataProposedTempGridEdit.Rows[0]["Proposed_DateBegin"].ToString();
                HdReviewIsActiveEdit.Text = dtGetDataProposedTempGridEdit.Rows[0]["IsActive_B"].ToString();
            }
            else
            {
                grProposedTempOrderBuyWithOrderBuyEdit.GetStore().RemoveAll();
            }
        }
        protected void GetDataProposedTempReview(int id)
        {
            var dtReview = new DataTable();
            dtReview = clsProposed.GetDataProposedGridEdit(id);
            if (dtReview != null && dtReview.Rows.Count > 0)
            {
                StoreOrderProposedReview.DataSource = dtReview;
                StoreOrderProposedReview.DataBind();

                if ((bool) dtReview.Rows[0]["IsActive_B"])
                {
                    lbProposedReViewTime.IconCls = "x-icon-tick";
                    lbProposedReviewDateUpdate.IconCls = "x-icon-tick";
                }
                if ((bool) dtReview.Rows[0]["IsActive_B"] == false)
                {
                    lbProposedReViewTime.IconCls = "x-icon-cross";
                    lbProposedReviewDateUpdate.IconCls = "x-icon-cross";
                }

                HDProposed_OrderIdBuyOrderEdit.Text = dtReview.Rows[0]["Proposed_ID"].ToString();
                lbProposedReviewCustomer_Alias.Text = dtReview.Rows[0]["Customer_Alias"].ToString();
                lbProposedReviewCustomer_Name.Text = dtReview.Rows[0]["Customer_Name"].ToString();
                lbProposedReviewOrderCode.Text = dtReview.Rows[0]["Proposed_TaxCode"].ToString();
                HdProposedReviewIsActive.Text = dtReview.Rows[0]["IsActive_B"].ToString();
                lbProposedReviewOrderDate.Text = String.Format("{0:dd-MM-yyyy}",
                    dtReview.Rows[0]["Proposed_DateBegin_B"]);
                if (dtReview.Rows[0]["Proposed_DateRespone_B"].ToString() == string.Empty ||
                    dtReview.Rows[0]["Proposed_DateRespone_B"].ToString() == DBNull.Value.ToString())
                {
                    lbProposedReviewDateUpdate.Text = "N/A";
                }
                else
                {
                    lbProposedReviewDateUpdate.Text = String.Format("{0:dd-MM-yyyy}",
                        dtReview.Rows[0]["Proposed_DateRespone_B"]);
                }
                if (dtReview.Rows[0]["Proposed_DateRespone_B"].ToString() == string.Empty ||
                    dtReview.Rows[0]["Proposed_DateRespone_B"].ToString() == DBNull.Value.ToString())
                {
                    lbProposedReViewTime.Text = "N/A";
                }
                else
                {
                    lbProposedReViewTime.Text = String.Format("{0:HH:mm:ss}", dtReview.Rows[0]["Proposed_DateRespone_B"]);
                }
            }
            else
            {
                grProposedOrderReview.GetStore().RemoveAll();
            }
        }
        
        protected void GetDataProposedSumEdit(int id)
        {
            var dtGetDataProposedSumEdit = new DataTable();
            dtGetDataProposedSumEdit = clsProposedDetail.GetDataProposedTempSumEdit(id);
            if (dtGetDataProposedSumEdit != null && dtGetDataProposedSumEdit.Rows.Count > 0)
            {
                lbQualityWithOrderEdit.Text = dtGetDataProposedSumEdit.Rows[0]["SOLUONG"].ToString();
                lbPriceWithOrderEdit.Text =
                    String.Format("{0:0,00}", dtGetDataProposedSumEdit.Rows[0]["TONGTIENMATHANG"]).Replace(".", ",");
                lbPriCKWithOrderEdit.Text =
                    String.Format("{0:0,00}", dtGetDataProposedSumEdit.Rows[0]["TONGTIENCK"]).Replace(".", ",");
                lbPriVATWithOrderEdit.Text =
                    String.Format("{0:0,00}", dtGetDataProposedSumEdit.Rows[0]["TONGTIENVAT"]).Replace(".", ",");
                lbTotalCostOrderWithOrderEdit.Text =
                    String.Format("{0:0,00}", dtGetDataProposedSumEdit.Rows[0]["TONGTIEN"]).Replace(".", ",");
            }
        }
        protected void GetDataProposedSumReview(int id)
        {
            var dtGetDataProposedSumReview = new DataTable();
            dtGetDataProposedSumReview = clsProposedDetail.GetDataProposedTempSumEdit(id);
            if (dtGetDataProposedSumReview != null && dtGetDataProposedSumReview.Rows.Count > 0)
            {
                lbTotalProposedMaterialReview.Text =
                    String.Format("{0:0,00}", dtGetDataProposedSumReview.Rows[0]["TONGTIEN"]).Replace(".", ",");
            }
        }
        protected bool CheckInsertMaterial(int id)
        {
            bool kiemtra = false;
            var dtCheckMaterial = new DataTable();
            dtCheckMaterial = clsProposedDetail.GetDataProposedTemp(int.Parse(Session["Users_Id"].ToString()));
            if (dtCheckMaterial != null && dtCheckMaterial.Rows.Count > 0)
            {
                foreach (DataRow dr in dtCheckMaterial.Rows)
                {
                    if (id == int.Parse(dr["Order_Buy_Detail_Id"].ToString()))
                    {
                        kiemtra = true;
                    }
                }
            }
            return kiemtra;
        }
        protected bool CheckInsertMaterialEdit(int id)
        {
            bool kiemtra = false;
            var dtCheckMaterial = new DataTable();
            dtCheckMaterial = clsProposedDetail.GetDataProposedTempEdit(int.Parse(Session["Users_Id"].ToString()),
                int.Parse(HD_OrderIdBuyOrderEdit.Text));
            if (dtCheckMaterial != null && dtCheckMaterial.Rows.Count > 0)
            {
                foreach (DataRow dr in dtCheckMaterial.Rows)
                {
                    if (id == int.Parse(dr["Order_Buy_Detail_Id"].ToString()))
                    {
                        kiemtra = true;
                    }
                }
            }
            return kiemtra;
        }
        protected bool CheckInsert()
        {
            bool kiemtra = false;
            DataTable dtCheckProposed = clsProposed.GetDataProposed(string.Empty);
            if (dtCheckProposed != null && dtCheckProposed.Rows.Count > 0)
            {
                foreach (DataRow dr in dtCheckProposed.Rows)
                {
                    if (txtChungTuOrderBuyOrderProposed.Text == dr["Proposed_TaxCode"].ToString())
                    {
                        kiemtra = true;
                    }
                }
            }
            return kiemtra;
        }
        protected void UpdateQualityTemp()
        {
            try
            {
                if (int.Parse(txtSoLuong.Text) > int.Parse(hdOrderQuanlity.Text))
                {
                    clsFormat.Alert_ERROR("Lỗi", "Số lượng đề nghị phải nhỏ hơn số lượng đang có !");
                }
                else
                {
                    var obj = new Proposed_Detail_ET
                    {
                        Proposed_Detail_ID = int.Parse(hdIdOrderTemp.Text),
                        Proposed_Quality = int.Parse(txtSoLuong.Text),
                        Order_Buy_Id = int.Parse(txt_OrderBuyOrderBuyOrderProposed.Text),
                        Proposed_Price = float.Parse(hdPrice.Text),
                        Materials_Id = int.Parse(hdMaterial.Text),
                        Proposed_DateBegin = DateTime.Parse(DateTime.Now.ToString()),
                        Proposed_Percent_CK = float.Parse(hdChietKhau.Text),
                        Proposed_Percent_VAT = float.Parse(hdVAT.Text),
                        Users_Id = int.Parse(Session["Users_Id"].ToString())
                    };
                    Proposed_Detail_BLL.UpdateQualityProposedDetailTemp(obj);
                    clsFormat.Alert_INFO("Thông Báo", "Cập nhật số lượng thành công !");
                    GetDataProposedTemp();
                    WindowProposedUpdateQualityProposedMaterial.Close();
                }
            }
            catch (Exception ex)
            {
                clsFormat.Alert_ERROR("Lỗi", "Có lỗi xảy ra trong quá trình xữ lý" + ex);
            }
        }
        protected void UpdateQualityTempEdit()
        {
            try
            {
                if (int.Parse(txtSoLuong.Text) > int.Parse(hdOrderQuanlity.Text))
                {
                    clsFormat.Alert_ERROR("Lỗi", "Số lượng đề nghị phải nhỏ hơn số lượng đang có !");
                }
                else
                {
                    var obj = new Proposed_Detail_ET
                    {
                        Proposed_Detail_ID = int.Parse(hdIdOrderTemp.Text),
                        Proposed_Quality = int.Parse(txtSoLuong.Text),
                        Proposed_Price = float.Parse(hdPrice.Text),
                        Proposed_DateBegin = DateTime.Parse(DateTime.Now.ToString()),
                        Proposed_Percent_CK = float.Parse(hdChietKhau.Text),
                        Proposed_Percent_VAT = float.Parse(hdVAT.Text),
                        Users_Id = int.Parse(Session["Users_Id"].ToString())
                    };
                    Proposed_Detail_BLL.UpdateQualityProposedDetailTempEdit(obj);
                    clsFormat.Alert_INFO("Thông Báo", "Cập nhật số lượng thành công !");
                    GetDataProposedTemp();
                    WindowProposedUpdateQualityProposedMaterial.Close();
                }
            }
            catch (Exception ex)
            {
                clsFormat.Alert_ERROR("Lỗi", "Có lỗi xảy ra trong quá trình xữ lý <br/>" + ex);
            }
        }
        protected void InsertProposed()
        {
            try
            {
                if (CheckInsert())
                {
                    clsFormat.Alert_WARNING("Thông Báo", "Mã chứng từ này đã tồn tại !");
                }
                else
                {
                    var dtcheckMaterial = new DataTable();
                    dtcheckMaterial = clsProposedDetail.GetDataProposedTemp(int.Parse(Session["Users_Id"].ToString()));
                    if (dtcheckMaterial != null && dtcheckMaterial.Rows.Count > 0)
                    {
                        var obj = new Proposed_ET();
                        obj.Proposed_TaxCode = txtChungTuOrderBuyOrderProposed.Text;
                        obj.Proposed_DateBegin = DateTime.Parse(txtNgayDatHangOrderBuyOrderProposed.Text);
                        obj.Users_Id = int.Parse(Session["Users_Id"].ToString());
                        obj.Proposed_Descripttion = txtDescriptionOrderBuyOrderProposed.Text;
                        Proposed_BLL.InsertProposed(obj);
                        clsFormat.Alert_INFO("Thông Báo", "Thêm mới thành công phiếu đề nghị nhập kho !");
                        GetDataProposedTemp();
                        GetDataProposed();
                        ClearText();
                    }
                    else
                    {
                        clsFormat.Alert_WARNING("Thông Báo", "Vui lòng chọn vật tư để lập phiếu đề nghị !");
                    }
                }
            }
            catch (Exception ex)
            {
                clsFormat.Alert_ERROR("Lỗi", "Có lỗi xảy ra trong quá trình cập nhật !" + ex);
            }
        }
        protected void UpdateProposed()
        {
            try
            {
                if (HdReviewIsActiveEdit.Text == "True")
                {
                    clsFormat.Alert_ERROR("Thông Báo",
                        "Phiếu đề nghị đã được xét duyệt.<br/>" + "Bạn không thể thay đổi phiếu đề nghị này !");
                }
                else
                {
                    var obj = new Proposed_ET();
                    obj.Proposed_ID = int.Parse(HD_OrderIdBuyOrderEdit.Text);
                    obj.Proposed_TaxCode_ = txtTaxCode_OrderBuyWithOrderEdit.Text;
                    obj.Proposed_Descripttion = txtDescriptstion_OrderBuyWithOrderEdit.Text;
                    Proposed_BLL.UpdateProposed(obj);
                    clsFormat.Alert_INFO("Thông Báo", "Cập nhật phiếu đề nghị thành công !");
                    GetDataProposed();
                }
            }
            catch (Exception ex)
            {
                clsFormat.Alert_ERROR("Thông Báo", "Có lỗi xảy ra trong quá trình cập nhật !<br/>" + ex);
            }
        }
        protected void ReviewProposed()
        {
            try
            {
                if (HdProposedReviewIsActive.Text == "True")
                {
                    clsFormat.Alert_ERROR("Thông Báo",
                        "Phiếu đề nghị này đã được xét duyệt rồi.<br/>" +
                        "Bạn không thể xét duyệt phiếu đề nghị này lần nữa !");
                }
                else
                {
                    var obj = new Proposed_ET();
                    obj.Proposed_ID = int.Parse(HDProposed_OrderIdBuyOrderEdit.Text);
                    obj.IsActive = true;
                    obj.Users_Id_Respone = int.Parse(Session["Users_Id"].ToString());
                    obj.Proposed_DateRespone = DateTime.Parse(DateTime.Now.ToString());
                    Proposed_BLL.ReviewProposed(obj);
                    clsFormat.Alert_INFO("Thông Báo", "Xét duyệt thành công !");
                    GetDataProposedTempReview(int.Parse(HDProposed_OrderIdBuyOrderEdit.Text));
                    GetDataProposed();
                }
            }
            catch (Exception ex)
            {
                clsFormat.Alert_ERROR("Lỗi", "Có lỗi xảy ra trong quá trình xét duyệt <br/>" + ex);
            }
        }
        protected void UnReviewProposed()
        {
            try
            {
                if (HdProposedReviewIsActive.Text == "False")
                {
                    clsFormat.Alert_ERROR("Thông Báo",
                        "Phiếu đề nghị này chưa được xét duyệt.<br/>" +
                        "Bạn không thể bỏ duyệt phiếu đề nghị này lần nữa !");
                }
                else
                {
                    var obj = new Proposed_ET();
                    obj.Proposed_ID = int.Parse(HDProposed_OrderIdBuyOrderEdit.Text);
                    obj.IsActive = false;
                    obj.Users_Id_Respone = int.Parse(Session["Users_Id"].ToString());
                    obj.Proposed_DateRespone = DateTime.Parse(DateTime.Now.ToString());
                    Proposed_BLL.ReviewProposed(obj);
                    clsFormat.Alert_INFO("Thông Báo", "Huỷ xét duyệt thành công !");
                    GetDataProposedTempReview(int.Parse(HDProposed_OrderIdBuyOrderEdit.Text));
                    GetDataProposed();
                }
            }
            catch (Exception ex)
            {
                clsFormat.Alert_ERROR("Lỗi", "Có lỗi xảy ra trong quá trình xét duyệt <br/>" + ex);
            }
        }
        #endregion

        #region[ClearText]
        protected void ClearText()
        {
            txtIDKhachHangOrderBuyOrderProposed.Text = string.Empty;
            txtCustomerAliasOrderBuyOrderProposed.Text = string.Empty;
            txtCustomerNameOrderBuyOrderProposed.Text = string.Empty;
            txt_OrderBuyOrderBuyOrderProposed.Text = string.Empty;
            txtIdCustomerOrderBuyOrderProposed.Text = string.Empty;
            txtOrderCodeOrderBuyOrderProposed.Text = string.Empty;
            txtAddressOrderBuyOrderProposed.Text = string.Empty;
            txtDescriptionOrderBuyOrderProposed.Text = string.Empty;
            txtOrderBuyCode.Text = string.Empty;
            txtChungTuOrderBuyOrderProposed.Text = string.Empty;
            txtNgayDatHangOrderBuyOrderProposed.Text = String.Format("{0:dd/MM/yyyy}", DateTime.Now);
            txtNgayGiaoHangOrderBuyOrderProposed.Text = String.Format("{0:dd/MM/yyyy}", DateTime.Now);

            grProposedTemp.GetStore().RemoveAll();

            //--------------------------------
            var dtCreateCode = new DataTable();
            dtCreateCode = clsProposed.GetDataProposed(string.Empty);
            if (dtCreateCode != null && dtCreateCode.Rows.Count > 0)
            {
                for (int i = 0; i < dtCreateCode.Rows.Count; i++)
                {
                    txtChungTuOrderBuyOrderProposed.Text = "PĐN" + "." + DateTime.Now.ToString("MMdd") + "-" + "000" +
                                                           Convert.ToString(
                                                               int.Parse(dtCreateCode.Rows[i]["Rows_ID"].ToString()));
                }
            }
            else
            {
                txtChungTuOrderBuyOrderProposed.Text = "PĐN" + "." + DateTime.Now.ToString("MMdd") + "-" + "0000";
            }
        }
        #endregion

        #region[Search]
        protected void Search_Event(object sender, DirectEventArgs e)
        {
        }
        protected void SearchMaterial_Event(object sender, DirectEventArgs e)
        {
        }
        #endregion

        #region[Print]
        protected void MenuItemExportExcel_Click(object sender, DirectEventArgs e)
        {
            var _clsGetServerUpload = new BLLsaddicServerUpload();
            var _dtGetServerUpload = _clsGetServerUpload.GetServerUpload();
            var sm = grProposed.GetSelectionModel() as CheckboxSelectionModel;
            if (sm != null)
                if (sm.SelectedRows.Count > 1)
                {
                    clsFormat.Alert_ERROR("Lỗi", "Bạn chỉ được phép chọn một dòng để in dữ liệu !");
                }
                else
                {
                    foreach (var row in sm.SelectedRows)
                    {
                        var _clsGetReport = new BllReportSell();
                        var _dtGetReport = _clsGetReport.GetReportProposed(int.Parse(row.RecordID));
                        if (_dtGetReport != null && _dtGetReport.Rows.Count > 0)
                        {
                            if (_dtGetServerUpload != null && _dtGetServerUpload.Rows.Count > 0)
                            {
                                LibGlobal.Export.ExcelExport(_dtGetReport,
                                    Server.MapPath(_dtGetServerUpload.Rows[5]["Path_Download"].ToString()),
                                    Server.MapPath(_dtGetServerUpload.Rows[5]["Path_Upload"].ToString()));
                                LibGlobal.Export.DownloadFile(
                                    _dtGetServerUpload.Rows[5]["Path_Download"].ToString(),
                                    _dtGetServerUpload.Rows[5]["Page_Name"].ToString(),
                                    _dtGetServerUpload.Rows[5]["Extend"].ToString());
                            }
                        }
                        clsFormat.Alert_INFO("Thông Báo", "In thành công !");
                    }
                }
        }
        #endregion

        #region[Permisstion]
        private void CheckPermisstion()
        {
            if (Session["login"] != null && Session["USer_Detail_Id"].ToString() != string.Empty)
            {
                bool Is_BtnAdd;
                bool Is_BtnEdit;
                bool Is_BtnView;
                bool Is_BtnDel;
                bool Is_BtnPrint;
                bool Is_BtnCancel;
                bool Is_BtnReview;

                SecurityServices.HasPermisstion_Btn(StringContent.Proposed, out Is_BtnAdd, out Is_BtnEdit, out Is_BtnDel, out Is_BtnView, out Is_BtnCancel, out Is_BtnPrint, out Is_BtnReview);
                if (Is_BtnAdd == false)
                {
                    btnAddNew.Visible = false;
                }
                if (Is_BtnEdit == false)
                {
                    btnEditMain.Visible = false;
                }
                if (Is_BtnView == false)
                {
                    PanelProposed.Visible = false;
                }
                if (Is_BtnDel == false)
                {
                    btnDel.Visible = false;
                }
                if (Is_BtnPrint == false)
                {
                    btnExport.Visible = false;
                }
                if (Is_BtnReview == false)
                {
                    btnProposedReview.Visible = false;
                }
                if (Is_BtnCancel == false)
                {
                    btnProposedUnReviewWindow.Visible = false;
                }
            }
        }
        private bool CheckPermisstionDobclick()
        {
            var check = false;
            if (Session["login"] != null && Session["USer_Detail_Id"].ToString() != string.Empty)
            {
                bool Is_BtnAdd;
                bool Is_BtnEdit;
                bool Is_BtnView;
                bool Is_BtnDel;
                bool Is_BtnPrint;
                bool Is_BtnCancel;
                bool Is_BtnReview;

                SecurityServices.HasPermisstion_Btn(StringContent.Proposed, out Is_BtnAdd, out Is_BtnEdit, out Is_BtnDel, out Is_BtnView, out Is_BtnCancel, out Is_BtnPrint, out Is_BtnReview);
                if (Is_BtnEdit == false)
                {
                    check = true;
                }
            }
            return check;
        }
        #endregion
    }
}